#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <muduo/base/CountDownLatch.h>
#include <iostream>
#include <string>

class DictCilent
{
public:
    DictCilent(const std::string &sip, const uint16_t sport)
    :_baseloop(_loopthread.startLoop()),
    _client(_baseloop, muduo::net::InetAddress(sip, sport), "DictClient"),
    _downlatch(1)
    {
        //设置connection回调
        _client.setConnectionCallback(std::bind(&DictCilent::OnConnection, this, std::placeholders::_1));
        //设置消息回调
        _client.setMessageCallback(std::bind(&DictCilent::OnMessage, this,
            std::placeholders::_1,
            std::placeholders::_2,
            std::placeholders::_3));
        
        //与服务器建立连接
        _client.connect();
        //进程同步
        _downlatch.wait();
    }
    bool send(const std::string &msg)
    {
        if (_conn->connected() == false)
        {
            std::cout << "连接已断开，消息发送失败" << std::endl;
            return false;
        }
        _conn->send(msg);
        return true;
    }

private:
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected() == true)
        {
            std::cout << "连接建立" << std::endl;
            _conn = conn;
            _downlatch.countDown();
        }
        else
        {
            std::cout << "连接断开" << std::endl;
            _conn.reset();
        }
    }

    void OnMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::string msg = buf->retrieveAllAsString();
        std::cout << msg << std::endl;
    }

private:
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop *_baseloop;
    muduo::CountDownLatch _downlatch;
    muduo::net::TcpConnectionPtr _conn;
    muduo::net::TcpClient _client;
};

int main()
{
    DictCilent dc("127.0.0.1", 9090);
    while(1)
    {
        std::string msg;
        std::cin >> msg;
        dc.send(msg);
    }
    return 0;
}